package com.example.demo001.utils;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {
    private static final String UNKNOWN_IP = "unknown";

    private IpUtils() {
    }
    /**
     * 获取客户端的真实 IP 地址
     *
     * @param request HttpServletRequest 对象
     * @return 客户端的 IP 地址
     */
    public static String getClientIPv4Address(HttpServletRequest request) {
        // 优先从 X-Forwarded-For 获取 IP 地址
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 如果 X-Forwarded-For 包含多个 IP 地址，取第一个有效 IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        // 确保返回的是 IPv4 地址
        if (isIPv4Address(ip)) {
            return ip;
        } else {
            return null; // 或者返回默认值
        }
    }

    private static boolean isIPv4Address(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }
        // 简化后的 IPv4 正则表达式
        String ipv4Pattern = "^((\\d{1,3}\\.){3}\\d{1,3})$";
        if (!ip.matches(ipv4Pattern)) {
            return false;
        }

        // 验证每个数字是否在 0-255 范围内
        String[] parts = ip.split("\\.");
        for (String part : parts) {
            try {
                int num = Integer.parseInt(part);
                if (num < 0 || num > 255) {
                    return false;
                }
            } catch (NumberFormatException e) {
                return false;
            }
        }
        return true;
    }
}
